#ifndef EMS_DEVICE_DEVICE_MANAGER_H
#define EMS_DEVICE_DEVICE_MANAGER_H

#include "device/DeviceBase.h"
#include "utils/Config.h"

#include <string>
#include <memory>
#include <vector>
#include <map>
#include <thread>
#include <atomic>
#include <mutex>

namespace ems {
namespace device {

class DeviceManager {
public:
    DeviceManager();
    ~DeviceManager();
    
    bool initialize();
    void start();
    void stop();
    
    bool addDevice(std::unique_ptr<DeviceBase> device);
    bool removeDevice(const std::string& deviceId);
    
    DeviceBase* getDevice(const std::string& deviceId);
    std::vector<DeviceBase*> getAllDevices();
    std::vector<DeviceBase*> getConnectedDevices();
    
    size_t getDeviceCount() const;
    size_t getConnectedDeviceCount() const;
    
    bool collectAllData(std::vector<std::pair<std::string, std::vector<DataValue>>>& data);
    bool reloadDevices();

private:
    std::map<std::string, std::unique_ptr<DeviceBase>> devices_;
    mutable std::mutex devicesMutex_;
    
    std::thread monitorThread_;
    std::atomic<bool> running_;
    
    void monitorDevices();
    std::unique_ptr<DeviceBase> createDevice(const utils::DeviceConfig& config);
    
    bool loadDevicesFromConfig();
};

}  // namespace device
}  // namespace ems

#endif  // EMS_DEVICE_DEVICE_MANAGER_H
